package org.serg.match3;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class GameActivity extends Activity {

	protected CustomApplication app;
	protected TextView player_name;
	protected TextView player_score;
	protected int previous_score;
	protected int current_score;
	protected int step;
	protected UserModel current_user;
	
	private Context context;
	private TableLayout main_table;
	
	private Map<Integer, Jewel> jewels;
	private List<Drawable> imgs;
	private ButtonListener button_listener;
	
	private ProcessJewelHandler handler1;
	
	private Jewel previous;
	private Jewel current;
	
	private int IMG_COUNT = 6;
	
	private int COL_COUNT = 6;
	private int ROW_COUNT = 7;
	
	protected PlayerDAO datasource;
	protected CustomSQLiteHelper dbHelper;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);
		
		dbHelper = CustomSQLiteHelper.getInstance(this);
        SQLiteDatabase database = dbHelper.open(); 
        datasource = new PlayerDAO(database);
		
		main_table = (TableLayout) findViewById(R.id.TableLayout01);
		context = main_table.getContext();
		button_listener = new ButtonListener();
		handler1 = new ProcessJewelHandler();
		previous = null;
		
		imgs = new ArrayList<Drawable>();
		imgs.add(getResources().getDrawable(R.drawable.f1));
		imgs.add(getResources().getDrawable(R.drawable.f2));
		imgs.add(getResources().getDrawable(R.drawable.f3));
		imgs.add(getResources().getDrawable(R.drawable.f4));
		imgs.add(getResources().getDrawable(R.drawable.f5));
		imgs.add(getResources().getDrawable(R.drawable.f6));
		//imgs.add(getResources().getDrawable(R.drawable.f7));
		
		
		//todo: in first generate structure with different elements
		// render table by structure 
		renderView(new Index<Integer, Integer>() {
	        @Override public Integer get(Integer position) {
	            return (int) (Math.random() * IMG_COUNT);
	        }
	    });
		
		app = (CustomApplication)getApplication();
		current_user = app.getPlayer();
        previous_score = current_user.getScore();
        current_score = 0;
        
        player_name = (TextView) findViewById(R.id.PlayerName);
        player_score = (TextView) findViewById(R.id.ScoreText);
        
        player_name.setText("Score of "+current_user.getName()+" is: ");
        player_score.setText("0");
	}
	
	
	
	private void renderView(Index<Integer, Integer> func) {
		
		TableRow tr = ((TableRow) findViewById(R.id.TableRow01));
		tr.removeAllViews();
		main_table = new TableLayout(context);
		tr.addView(main_table);
		
		jewels = new HashMap<Integer, Jewel>();
		for (int x=0; x<ROW_COUNT; x++) {
			TableRow row = new TableRow(context);
			row.setHorizontalGravity(Gravity.CENTER);
			
			for (int y=0; y<COL_COUNT; y++) {
				int index = (x * COL_COUNT) + y;
				//int rand = (int)(Math.random() * IMG_COUNT);
				int rand = (int) func.get(index);
				Drawable img = imgs.get(rand);
			
				ImageView cell = new ImageView(context);
				cell.setPadding(5, 5, 5, 5);
				cell.setImageDrawable(img);
				cell.setId(index);
				cell.setOnClickListener(button_listener);
				row.addView(cell);
				
				System.out.println("item "+Integer.toString(index)+" rand "+Integer.toString(rand));
				
				Jewel el = new Jewel(cell, img, rand, index);
				jewels.put(index, el);
			}
			main_table.addView(row);
		}
		
	}
	
	private Integer getNextIndex(int coll, int current) {
		for (int x=(ROW_COUNT-1); x>=0; x--) {
			int index = (x * COL_COUNT) + coll;
			
			if (index >= current) {
				continue;
			}
			
			Jewel element = jewels.get(index);
			if (element.isblock()) {
				continue;
			}
			
			element.block();
			return element.getIndex();
		}
		return null;
	}
	
	private void rebuildView(int blocked) {
		// 1- position, 2 - index
		final Map<Integer, Integer> items = new HashMap<Integer, Integer>();
		//generate new structure
		for (int y=0; y<COL_COUNT; y++) {
			for (int x=(ROW_COUNT-1); x>=0; x--) {
				int index = (x * COL_COUNT) + y;
				Integer rand;
				
				Jewel item = jewels.get(index);
				if (item.isblock()) {
					//rand = Utility.getNextIndex(y, index, jewels, ROW_COUNT);
					rand = getNextIndex(y, index);
				} else {
					rand = item.getIndex();
				}
				items.put(index, rand);
			}
		}
		
		//get new elements
		final List<Integer> new_indexes = Utility.getNewElements(blocked, IMG_COUNT);
		//rebuild view
		renderView(new Index<Integer, Integer>() {
	        @Override public Integer get(Integer position) {
	        	Integer index = items.get(position);
	        	if (index == null) {
	        		int last = new_indexes.size()-1;
	        		return new_indexes.remove(last);
	        	}
	            return index;
	        }
	    });
		player_score.setText(Integer.toString(current_score));
		if (current_score > current_user.getScore()) {
			current_user.setScore(current_score);
			datasource.updatePlayer(current_user);
		}
		
	}
	
	
	class ButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			System.out.println("On click 1");
			int index = v.getId();
			current = jewels.get(index);
			//if (current.isblock()) {
			//	return;
			//}
			
			System.out.println("On click 2");
			if (previous == null) {
				//current.block();
				previous = current;
				
				previous.getCell().setBackgroundColor(
						Color.parseColor("#FFFFFF"));
				return;
			}
			
			System.out.println("On click 4");
			Utility.switchElements(current, previous);
			
			TimerTask tt = new TimerTask() {
				@Override
				public void run() {
					try {
						handler1.sendEmptyMessage(0);
					} catch (Exception e) {
						Log.e("E1", e.getMessage());
					}
				}
			};

			Timer t = new Timer(false);
			t.schedule(tt, 1000);
		}
	}
	
	class ProcessJewelHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			System.out.println("On click 3");
			int direction = Utility.isNeighbor(current.getPosition(), previous.getPosition(), COL_COUNT);
			//int direction = isNeighbor(current.getPosition(), previous.getPosition());
			if (direction == 0) {
				//previous.unblock();
				
				previous.getCell().setBackgroundColor(
						Color.parseColor("#000000"));
				Utility.switchElements(current, previous);
				previous = null;
				return;
			}
			
			System.out.println("On click 5");
			List<Jewel> blocked = Utility.isGroup(current, jewels, COL_COUNT, ROW_COUNT);
			//List<Jewel> blocked = isGroup(current);
			if (blocked.size() <= 0) {
				previous.getCell().setBackgroundColor(
						Color.parseColor("#000000"));
				Utility.switchElements(current, previous);
				previous = null;
				return;
			}
			
			System.out.println("On click 6");
			//Drawable ic_launcher = getResources().getDrawable(R.drawable.ic_launcher);
			for (Jewel jewel : blocked) {
				System.out.println("DELETED "+Integer.toString(jewel.getPosition()));
				jewel.block();
			}
			
			System.out.println("On click 7");
			
			previous.getCell().setBackgroundColor(
					Color.parseColor("#000000"));
			previous = null;
			
			current_score = current_score + Utility.getScore(blocked.size());
			rebuildView(blocked.size());
		}
	}
}
